import React, { Component } from 'react';
import classNames from 'classnames';
import Checkbox from './index';

export default class CheckboxGroup extends Component {
  static defaultProps = {
    options: [],
    prefixCls: 'checkbox-group'
  };

  constructor(props) {
    super(props);

    this.state = {
      value: props.value || props.defaultValue || []
    };
  }

  componentWillReceiveProps(nextProps) {
    if ('value' in nextProps) {
      this.setState({
        value: nextProps.value || []
      });
    }
  }

  getOptions() {
    const { options } = this.props;
    return options.map((option) => {
      if (typeof option === 'string') {
        return {
          label: option,
          value: option
        };
      }
    });
  }

  toggleOption = (option) => {
    const optionIndex = this.state.value.indexOf(option.value);
    const value = [...this.state.value];
    if (optionIndex === -1) {
      value.push(option.value);
    } else {
      value.splice(optionIndex, 1);
    }
    if (!('value' in this.props)) {
      this.setState({ value });
    }
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(value);
    }
  }
  render() {
    const { prefixCls, className } = this.props;
    const options = this.getOptions().map(option =>
      <Checkbox
        disabled={'disabled' in option ? option.disabled : this.props.disabled}
        checked={this.state.value.indexOf(option.value) !== -1}
        onChange={() => this.toggleOption(option)}
        className={`${prefixCls}-item`}
        key={option.value}
      >
        {option.label}
      </Checkbox>
    );
    const classString = classNames(prefixCls, className);
    return (
      <div className={classString}>
        {options}
      </div>
    );
  }
}
